package com.sh3h.generator.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import com.sh3h.generator.web.domain.GenFieldType;
import com.sh3h.generator.web.dtos.GenFieldTypeDto;
import com.sh3h.generator.web.dtos.Result;
import com.sh3h.generator.web.service.impl.GenFieldTypeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping({"/api/gen/fieldtypes"})
public class FieldTypeController {
    @Autowired
    private GenFieldTypeServiceImpl fieldTypeService;

    @GetMapping("")
    public Result getByPage(int pageNum, int pageSize, String attrType, String columnType) {
        Page<GenFieldType> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<GenFieldType> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isNullOrEmpty(attrType)) {
            queryWrapper.eq(GenFieldType::getAttrType, attrType);
        }
        if (!StringUtils.isNullOrEmpty(columnType)) {
            queryWrapper.eq(GenFieldType::getColumnType, columnType);
        }
        Page<GenFieldType> datasourceList = fieldTypeService.page(page, queryWrapper);
        return Result.success(datasourceList);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") String id) {
        GenFieldType datasource = fieldTypeService.getById(id);
        return Result.success(datasource);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") String id) {
        Boolean result = fieldTypeService.removeById(id);
        return Result.success(result);
    }

    @PutMapping("/{id}")
    public Result updateById(@RequestBody GenFieldTypeDto dto) {
        GenFieldType datasource = GenFieldTypeDto.ToModal(dto);
        Boolean result = fieldTypeService.updateById(datasource);
        return Result.success(result);
    }

    @PostMapping("")
    public Result insert(@RequestBody GenFieldTypeDto dto) {
        GenFieldType datasource = GenFieldTypeDto.ToModal(dto);
        Boolean result = fieldTypeService.save(datasource);
        return Result.success(result);
    }
}
